<template lang="html">
  <div class="">
    <div class="add">
      <el-button type="primary" @click="add">新增题目</el-button>
    </div>
    <tableVue :list="list" :state="false" v-loading="pageData.loading" :pagination="true">
        <slot>
          <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="compile(scope.row)">编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  class="del"
                  @click="del(scope.row,2)">删除</el-button>
              </template>
          </el-table-column>
        </slot>
    </tableVue>
    <el-dialog title="新增题目" :visible.sync="outerVisible"    width="62%">
        <div class="dialogBox">
            <div class="let">
              <el-form :model="pageData" ref="ruleForm" label-width="80px" class="demo-ruleForm">
                <el-form-item label="添加题目">
                    <el-input v-model="pageData.categoryName" placeholder="请输入内容"></el-input>
                 </el-form-item>
                 <el-button type="primary" class="boban" @click="selectTemplate">选择模板</el-button>
                 <el-form-item label="最多选择">
                     <el-input v-model="pageData.multipleMax" placeholder="请输入内容"></el-input>
                  </el-form-item>
                  <el-form-item label="估计顺序">
                      <el-input v-model="pageData.ordinal" placeholder="请输入内容"></el-input>
                   </el-form-item>
                   <el-form-item label="别名" v-if="aliasName !== '否'">
                       <el-input v-model="pageData.aliasName" placeholder="请输入内容"></el-input>
                    </el-form-item>
                  <el-form-item label="是否多选">
                    <el-select v-model="pageData.isMultiple" placeholder="请选择">
                        <el-option value="">请选择</el-option>
                        <el-option
                          v-for="item in Multiple"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                   </el-form-item>
                   <el-form-item label="图片" prop="imgUrl">
                         <el-upload
                          class="upload-demo"
                          :auto-upload='false'
                          :on-change="upload"
                          :on-remove="handleRemove"
                          :file-list="pageData.fielList"
                          action="https://jsonplaceholder.typicode.com/posts/"
                          :list-type="String"
                          list-type="picture">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                   </el-form-item>
              </el-form>

            </div>
            <div class="rgt">
              <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="80px" class="demo-ruleForm">
                <div class="qqq">
                  <div class="optionBox" v-for="(domain, index) in dynamicValidateForm.domains">
                      <el-form-item label="添加选项"
                        :label="'选项' + index"
                        :key="domain.key"
                        :prop="'domains.' + index + '.value'">
                        <el-input placeholder="请输入内容" v-model='domain.optionName'></el-input>
                        <p class="p_span"><span>别名</span><el-input placeholder="请输入内容" v-model="domain.aliasName"></el-input></p>
                        <p class="p_span istype">
                          <span>估计方式</span>
                          <el-select v-model="domain.reduceType" placeholder="请选择" @change="getType(domain,index)">
                              <el-option value="">请选择</el-option>
                              <el-option
                                v-for="item in isreduceType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                              </el-option>
                          </el-select>
                        </p>
                        <p class="p_span istype" v-show="domain.ispercent"><span>百分比</span><el-input placeholder="请输入内容" v-model="domain.reducePercent"></el-input></p>
                        <p class="p_span istype" v-show="domain.isfixation"><span>固定金额</span></span><el-input placeholder="请输入内容" v-model="domain.reduceAmount"></el-input></p>
                        <el-button @click.prevent="removeDomain(domain)" type="danger">删除</el-button>
                     </el-form-item>
                  </div>
                </div>
                  <el-button @click="addDomain" type="primary" class="addxu">新增选项</el-button>
              </el-form>
            </div>
        </div>
     <el-dialog
       width="30%"
       title="选择模板"
       :visible.sync="innerVisible"
       append-to-body>
       <el-form ref="ruleForm" label-width="80px" class="demo-ruleForm">
         <el-form-item label="选择分类">
           <el-cascader
              v-model="pageData.categoryId"
              placeholder="试试搜索：手机"
              :options="isClsssList"
              :props="props"
              @change="getTemplate"
              filterable
            ></el-cascader>
          </el-form-item>
           <el-form-item label="选择模板">
             <el-select v-model="istemplateVal" placeholder="请选择">
                 <el-option value="">请选择</el-option>
                 <el-option
                   v-for="item in istemplate"
                   :key="item.value"
                   :label="item.conditionName"
                   :value="item.conditionTplId">
                 </el-option>
               </el-select>
            </el-form-item>
            <div class="dialog-footer">
              <el-button @click="innerVisible = false">取 消</el-button>
              <el-button type="primary" @click="istempconfirm">确定</el-button>
            </div>
        </el-form>
     </el-dialog>
     <div slot="footer" class="dialog-footer">
       <el-button @click="outerVisible = false">取 消</el-button>
       <el-button type="primary" v-if="btnState == '1'" @click="confirm('post')">确定</el-button>
       <el-button type="primary" v-if="btnState == '2'" @click="confirm('put')">更新</el-button>
     </div>
   </el-dialog>
  </div>
</template>

<script>
import Data from './qaData.js'
import dialogVue from '@/components/dialog.vue'
import tableVue from '@/components/alltable.vue'
import { Base64 } from 'js-base64';
import {
  productConditionList,
  getAllPcot,
  getAllTemplate,
  allProudctClass,
  addProductQa,
  delProuductQa,
  getProuductQa,
  getQaOption
} from "@/api/product/product";
  export default {
    components : {
      tableVue,
      dialogVue
    },
    data () {
      return JSON.parse(JSON.stringify(Data))
    },
    mounted () {
      this.getProuductQaList();
      this.getAllProudctClass();
    },
    methods : {
      getProuductQaList () {
        // this.pageData.loading = false;
        getProuductQa(this.$route.query.item).then(res=>{
          if (res.data.code == 'OK') {
            this.pageData.loading = false;
            this.list.tbody = res.data.data.map(item=>{
              item.gmtCreate = this.switchTime(item.gmtCreate);
              item.gmtUpdate = this.switchTime(item.gmtUpdate);
              return item;
            });
          }
        })
      },
      confirm (method) {

        var url = this.pageData.fielList.map((item)=>{return item.url})
        let data = {
          conditionId : this.conditionId = this.conditionId == '' ? null : this.conditionId,
          conditionName : this.pageData.categoryName,
          aliasName : this.pageData.aliasName,
          isMultiple : this.pageData.isMultiple,
          multipleMax : this.pageData.multipleMax,
          ordinal : this.pageData.ordinal,
          productId :this.$route.query.item,
          exampleImgs : JSON.stringify(url),
          imgs : this.pagefileUrl.map((item)=>{return item.base64Url}),
          options : this.dynamicValidateForm.domains.map((item)=>{
            return {
              optionName :item.optionName,
              aliasName : item.aliasName,
              reduceType : item.reduceType,
              reducePercent : item.reducePercent = item.reducePercent == undefined ? null : item.reducePercent,
              reduceAmount : item.reduceAmount = item.reduceAmount == undefined ? null : item.reduceAmount,
            }
          })
        };

        for (var i = 0; i < data.options.length; i++){
            if (data.options[i].reducePercent >= 1 || data.options[i].reducePercent < 0 ) {
               this.$message.error('百分比只能输入小于1的数字并且大于等于0');
                 return false
            }
        }
        addProductQa(data,method).then(res=>{
          if (res.data.code == 'OK') {
              this.outerVisible = false;
              if (method == 'post') {
                  this.$message.success('新增成功');
                  this.getProuductQaList();
              } else if (method == 'put') {
                this.$message.success('编辑成功');
                this.getProuductQaList();
              }
          } else {
            this.$message.error(res.data.message)
          }
        })
      },
      getTemplate () {//根据分类拉取模板
        getAllTemplate(this.pageData.categoryId[this.pageData.categoryId.length - 1]).then(res=>{
            if (res.data.code == 'OK') {
              if (res.data.data.records.length > 0) {
                this.templatemAllData = res.data.data.records;
                this.istemplate = res.data.data.records.map(item=>{
                     this.istemplate = item.options;
                     return item;
                });
              } else {
                this.istemplate = [];
                this.istemplateVal = '';
              }
            }
        })
      },
      getAllProudctClass () {
        allProudctClass().then(res=>{
          if (res.data.code == 'OK') {
            this.isClsssList = res.data.data.map(item=>{
              if (item.childrens.length == 0) {
                  delete item.childrens
              }
              return item
            });
          }
        })
      },
      getType (domain,index) {//选择方式
        domain.reducePercent = '';
        domain.reduceAmount = '';
        if (domain.reduceType == 'PERCENT') {
          this.dynamicValidateForm.domains[index].ispercent = true;
          this.dynamicValidateForm.domains[index].isfixation = false;
        } else if (domain.reduceType == 'AMOUNT') {
          this.dynamicValidateForm.domains[index].isfixation = true;
          this.dynamicValidateForm.domains[index].ispercent = false;
        } else {
          this.dynamicValidateForm.domains[index].ispercent = false;
          this.dynamicValidateForm.domains[index].isfixation = false;
        }
      },
      selectTemplate () {//选择模板
        this.innerVisible = true;
        this.pageData.fielList = []

      },
      istempconfirm (val) {//根据条件id获取全部条件对应的选项
        getAllPcot(this.istemplateVal).then(res=>{
            if (res.data.code == 'OK') {
                this.innerVisible = false;
                this.dynamicValidateForm.domains = res.data.data;
                this.templatemAllData.map(item=>{
                  if (item.conditionTplId == this.istemplateVal) {
                      this.pageData.categoryName = item.conditionName;
                      this.pageData.multipleMax = item.multipleMax;
                      this.pageData.isMultiple = item.isMultiple;
                      this.pageData.isAlias = item.isAlias;
                      JSON.parse(item.exampleImgs).map(item=>{
                          this.pageData.fielList.push({
                            name : '',
                            url : item
                          })
                        })
                  }
                })
            }
        })
      },
      addDomain() {//新增选项
         this.dynamicValidateForm.domains.push({
           value: '',
           key: Date.now()
         });
       },
       removeDomain(item) {//删除选项
         var index = this.dynamicValidateForm.domains.indexOf(item)
         if (index !== -1) {
           this.dynamicValidateForm.domains.splice(index, 1)
         }
       },
      upload (file,fileList) {//拿到图片的地址
           let reader = new FileReader();
           reader.readAsDataURL(file.raw);
           reader.onload =  () => {
            this.pagefileUrl.push({
              base64Url:reader.result.split(',')[1],
              url:file.url
            });
           }
      },
      handleRemove(file, fileList) {
        this.pageData.fielList.map((item,idx,arr)=> {
            if (file.url == item.url) {
                arr.splice(idx,1);
            }
        });
        this.pagefileUrl.map((item,idx,arr)=> {
            if (file.url == item.url) {
                arr.splice(idx,1)
            }
        });
      },
      compile (item) {
        this.btnState = '2'
        this.pageData.fielList = [];
        this.outerVisible = true;
        this.conditionId = item.conditionId
        getQaOption(item.conditionId,this.$route.query.item).then(res=>{
          if (res.data.code == 'OK') {
            this.dynamicValidateForm.domains = res.data.data;
             res.data.data.map(item=>{
              if (item.reduceType == null) {
                item['ispercent'] = false;
                item['isfixation'] = false;
                return false
              }
               if (item.reduceType == 'AMOUNT') {
                 item['ispercent'] = false;
                 item['isfixation'] = true;
               } else {
                  item['ispercent'] = true;
                  item['isfixation'] = false;
               }
             })

            this.pageData.categoryName = item.conditionName;
            this.pageData.multipleMax = item.multipleMax;
            this.pageData.ordinal = item.ordinal;
            this.pageData.isMultiple = item.isMultiple;
            if (JSON.parse(item.exampleImgs)) {
              JSON.parse(item.exampleImgs).map(item=>{
                  this.pageData.fielList.push({
                    name : '',
                    url : item
                  })
                })
            }
          }
        })
      },
      add () {
        this.outerVisible = true;
        this.btnState = '1'
        this.pageData = {};
        this.pageData.fielList = [];
        this.dynamicValidateForm.domains = [];
      },
      del (id) {
        this.delMessage(()=>{
          var ids = [{
              conditionId : id.conditionId,
              productId : this.$route.query.item
          }]
          delProuductQa(ids).then(res=>{
            if (res.data.code == 'OK') {
                this.$message.success('删除成功');
                this.getProuductQaList();
            } else {
              this.$message.error(res.data.message);
            }
          })
        })
      }
    }
  }
</script>

<style scoped>
.confirm {
  position: absolute;
  bottom: -1px;
  right: 100px;
}
.dialogBox {
  display: flex;
}
.let {
  position:relative;
      width: 404px;
}
.boban {
  position: absolute;
  top: -26px;
left:25px;
}
.addxu {
  margin-top: 20px;
}
.dialog-footer {
  display: flex;
justify-content: flex-end;
}
.p_span {
  position: relative;
}
.p_span span{
  position: absolute;
  left:-43px;
}
.istype span {
  position: absolute;
  left:-70px;
}
.optionBox:nth-child(1),.optionBox:nth-child(2){
  margin-top: 0;
}
.qqq {
  display: flex;
  flex-wrap: wrap;
  width: 615px;
}
.optionBox{
  border:1px solid #ccc;
  padding: 20px 20px 0 0;
  margin-top: 10px;
  border-radius: 4px;
  margin-right: 5px;
}
</style>
